package com.situ.music.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.situ.music.R;
import com.situ.music.service.MusicService;

import java.io.File;
import java.util.ArrayList;

public class MusicPlayActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MusicPlayActivity";

    // 当前正在播放的歌曲的路径
    private String path;
    // 当前目录下面所有的mp3歌曲
    private ArrayList<String> mp3List;
    // 记录当前正在播放的歌曲在mp3List中的索引
    private int currentMusicIndex;
    private MusicService.MusicController musicController;

    private static SeekBar seekBar;
    private static TextView tvProgress;
    private static TextView tvTotal;
    private ImageView ivPrevious;
    private ImageView ivPlay;
    private ImageView ivNext;

    // 在Service或者线程里面是不能直接更新主线程中的UI控件，
    // 需要先交给Handler，然后再更新UI
    public static Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            Bundle bundle = msg.getData();
            int duration = bundle.getInt("duration");
            int currentPosition = bundle.getInt("currentPosition");
            seekBar.setMax(duration);
            seekBar.setProgress(currentPosition);
            // 总的播放时长
            int minute = duration / 1000 / 60;
            int second = duration / 1000 % 60;
            tvTotal.setText(minute + ":" + second);

            // 已经播放时长
            int currentMinute = currentPosition / 1000 / 60;
            int currentSecond = currentPosition / 1000 % 60;
            tvProgress.setText(currentMinute + ":" + currentSecond);
        }
    };


    private ServiceConnection connection = new ServiceConnection() {
        // 当绑定上Service服务时候调用这个方法
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected");
            musicController = (MusicService.MusicController) service;
            musicController.init(path);
        }

        // 当Service断开时候调用这个方法
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected");
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_play);

        initView();
        initData();
        bindService();
    }

    // 绑定Service
    private void bindService() {
        Intent intent = new Intent(this, MusicService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }

    private void initData() {
        Intent intent = getIntent();
        path = intent.getStringExtra("path");
        Log.d(TAG, path);
        mp3List = (ArrayList<String>) intent.getSerializableExtra("mp3List");
        currentMusicIndex = mp3List.indexOf(path);
    }

    private void initView() {
        seekBar = findViewById(R.id.seekBar);
        tvProgress = findViewById(R.id.tv_progress);
        tvTotal = findViewById(R.id.tv_total);
        ivPrevious = findViewById(R.id.iv_previous);
        ivPlay = findViewById(R.id.iv_play);
        ivNext = findViewById(R.id.iv_next);
        ivPrevious.setOnClickListener(this);
        ivPlay.setOnClickListener(this);
        ivNext.setOnClickListener(this);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            // 滑动条拖动
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            // 开始滑动
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            // 停止滑动
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 得到当前停止的位置
                int progress = seekBar.getProgress();
                musicController.seekTo(progress);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_previous:
                if (currentMusicIndex == 0) {
                    Toast.makeText(this, "现在已经播放的是第一首歌曲", Toast.LENGTH_LONG).show();
                    return;
                }
                Log.d(TAG, "previous");
                currentMusicIndex--;
                musicController.init(mp3List.get(currentMusicIndex));
                ivPlay.setImageDrawable(getResources().getDrawable(R.drawable.playbar_pause));
                break;
            case R.id.iv_play:
                if (musicController.isPlaying()) {// 播放状态
                    musicController.pause();
                    ivPlay.setImageDrawable(getResources().getDrawable(R.drawable.playbar_play));
                } else {
                    musicController.play();
                    ivPlay.setImageDrawable(getResources().getDrawable(R.drawable.playbar_pause));

                }
                break;
            case R.id.iv_next:
                if (currentMusicIndex == mp3List.size() - 1) {
                    Toast.makeText(this, "现在已经播放的是最后一首歌曲", Toast.LENGTH_LONG).show();
                    return;
                }
                Log.d(TAG, "next");
                currentMusicIndex++;
                musicController.init(mp3List.get(currentMusicIndex));
                ivPlay.setImageDrawable(getResources().getDrawable(R.drawable.playbar_pause));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解绑Service
        musicController.releasePlayer();
        // 解绑服务
        unbindService(connection);
    }
}